import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router'

// 创建 Axios 实例
const axiosInstance = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 10000, // 请求超时时间
  headers: {'content-type': 'application/x-www-form-urlencoded'}
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  async (config) => {
    
    const token = localStorage.getItem('token');

    if (token || config.url=="/staff/login") {
      config.headers['token'] = token;
    }else{
      // ElMessage.error('请登录');
      await router.push({name:"login"})
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  async (response) => {
    if(response.data.code==403){
      ElMessage.error({
        message: response.data.message,
        grouping: true,
        type: 'error',
        duration:1500,
        onClose:async function() {
          await router.push({name:"login"})
        }
      }
      );
    }else if(response.data.code==500){
      ElMessage.error(response.data.message);
      return Promise.reject(response.data);
    }else{
      return response;
    }
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('未授权，请重新登录');
          break;
        case 403:
          ElMessage.error('拒绝访问');
          break;
        case 404:
          ElMessage.error('请求地址出错');
          break;
        case 500:
          ElMessage.error('服务器内部错误');
          break;
        default:
          ElMessage.error('请求失败');
      }
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
